<template>
  <div v-if="wxLogin" class="wx-login-dialog">
    <div class="welogin">
      <div v-if="qrCodeUrl">
        <qrcode-vue :value="qrCodeUrl" :size="200" />
      </div>
      <h2>请使用微信扫码登录</h2>
      <div class="close-btn" @click="switchToNormalLogin">取消</div>
    </div>
  </div>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large" v-if="!wxLogin">
    <el-form-item prop="username">
      <el-input v-model="loginForm.account" placeholder="用户名：s">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码：1" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="validCode">
      <div style="display: flex; align-items: center">
        <el-input v-model="loginForm.validCode" placeholder="请输入验证码" style="width: 50%" />
        <ValidCode v-model="generatedCode" style="margin-left: 20px" />
      </div>
    </el-form-item>
  </el-form>
  <div class="login-btn" v-if="!wxLogin">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
  <div class="over-btn" v-if="!wxLogin">
    <div class="wechat" @click="switchToWxLogin">
      <img src="@/assets/icons/wechat.png" alt="微信登录" class="images" />
    </div>
    <div class="qqtent">
      <img src="@/assets/icons/qq1.webp" alt="微信登录" class="images" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import ValidCode from "./ValidCode.vue";
import QrcodeVue from "qrcode.vue";
import { ElMessage, ElNotification } from "element-plus";
import { getUserInfoApi, loginApis, getWxLoginQrApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/admin";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
import { getTimeState } from "@/utils";
import { useInfoStore } from "@/stores/modules/info";
import { getQrGenerate, getQrStatus } from "@/api/modules/qrLogin";

const router = useRouter();

const wxLogin = ref(false); // 控制是否显示微信扫码登录
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
interface GenerateQrRes {
  loginKey: string;
  status: string;
}

interface StatusRes {
  status: string;
}
const qrCodeUrl = ref<string>("");
const loginKey = ref<string>("");
const status = ref<string>("等待扫码...");

const generatedCode = ref("");
const loginRules = reactive({
  phone: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
  // validCode: [
  //   {
  //     validator: (rule: any, value: string, callback: any) => {
  //       if (!value) {
  //         ElMessage.error("请输入验证码");
  //         return callback(new Error("请输入验证码"));
  //       }
  //       if (value.toLowerCase() !== generatedCode.value.toLowerCase()) {
  //         ElMessage.error("验证码错误");
  //         return;
  //       }
  //       callback();
  //     },
  //     trigger: "blur"
  //   }
  // ]
});

const loading = ref(false);
const loginForm = reactive({
  account: "s",
  password: "1"
});
//<Login.ReqLoginForm> validCode: ""
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const response = await loginApis(loginForm);
      const { data } = response;
      // 设置用户信息到store
      userStore.setToken(data.token);
      userStore.setUserId(data.id);
      userStore.setIsSuper(data.isSuper);

      const res = await getUserInfoApi();
      useInfoStore().setInfo({
        avatar: res.data.avatar,
        email: res.data.email,
        gender: res.data.gender,
        nickName: res.data.nickname
      });
      // 2.添加动态路由
      await initDynamicRouter();
      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 衣合客栈后台管理系统",
        type: "success",
        duration: 3000
      });
    } catch (error) {
      ElMessage.error("登录失败，请检查网络连接");
    } finally {
      loading.value = false;
    }
  });
};
// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 切换回正常登录表单
const switchToNormalLogin = () => {
  wxLogin.value = false;
};

const switchToWxLogin = async () => {
  wxLogin.value = true;
  try {
    // 生成二维码
    const res: GenerateQrRes = await getQrGenerate();
    loginKey.value = res.loginKey;
    console.log("loginKey:", loginKey.value);
    // 二维码内容（手机扫码后访问的确认页面地址）
    // qrCodeUrl.value = `http://192.168.1.103:8848/scanConfirm?loginKey=${loginKey.value}`;
    qrCodeUrl.value = `http://192.168.1.103:8848/scanConfirm?loginKey=${loginKey.value}`;
    console.log("二维码 URL:", qrCodeUrl.value);
    // 轮询状态
    const timer = setInterval(async () => {
      const s: StatusRes = await getQrStatus(loginKey.value);
      status.value = s.status;
      if (s.status.startsWith("CONFIRMED")) {
        clearInterval(timer);
        // alert("登录成功，用户ID: " + s.status.split(":")[1]);
        loading.value = true;
        // 1.执行登录接口
        const response = await loginApis(loginForm);
        const { data } = response;
        // 设置用户信息到store
        userStore.setToken(data.token);
        userStore.setUserId(data.id);
        userStore.setIsSuper(data.isSuper);
        const res = await getUserInfoApi();
        useInfoStore().setInfo({
          avatar: res.data.avatar,
          email: res.data.email,
          gender: res.data.gender,
          nickName: res.data.nickname
        });
        // 2.添加动态路由
        await initDynamicRouter();
        // 3.清空 tabs、keepAlive 数据
        tabsStore.setTabs([]);
        keepAliveStore.setKeepAliveName([]);
        // 4.跳转到首页
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: "欢迎登录 衣合客栈后台管理系统",
          type: "success",
          duration: 3000
        });
        loading.value = false;
      }
    }, 2000);
  } catch (err) {
    console.error("生成二维码失败", err);
  }
};
onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
// 点击微信登录按钮

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";
</style>
